import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:hm_show_flutter/utils/permission_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

class PhotoGalleryPage extends StatefulWidget {
  final List photoList;
  final int index;

  PhotoGalleryPage({this.photoList, this.index});

  @override
  _PhotoGalleryPageState createState() => _PhotoGalleryPageState();
}

class _PhotoGalleryPageState extends State<PhotoGalleryPage> {
  @override
  int currentIndex = 0;
  int initialIndex; //初始index
  int length;
  int title;

  String imgUrl;

  @override
  void initState() {
    currentIndex = widget.index;
    initialIndex = widget.index;
    length = widget.photoList.length;
    title = initialIndex + 1;
    imgUrl = widget.photoList[0];
    super.initState();
  }

  void onPageChanged(int index) {
    setState(() {
      currentIndex = index;
      title = index + 1;
      imgUrl = widget.photoList[index];
    });
  }

  _saveImage(String url) async {
    if (url == null) {
      ToastUtil.showToast("url error");
      return;
    }
    try {
      var response = await Dio()
          .get(url, options: Options(responseType: ResponseType.bytes));
      final result =
          await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
      if (result != null) {
        ToastUtil.showToast("保存成功");
      } else {
        ToastUtil.showToast("保存失败");
      }
    } catch (e) {
      ToastUtil.showToast("保存失败");
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        title: Text(
          '${title} / ${length}',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
      ),
      body: Container(
          decoration: BoxDecoration(
            color: Colors.black,
          ),
          constraints: BoxConstraints.expand(
            height: MediaQuery.of(context).size.height,
          ),
          child: Stack(
            alignment: Alignment.bottomRight,
            children: <Widget>[
              PhotoViewGallery.builder(
                scrollDirection: Axis.horizontal,
                scrollPhysics: const BouncingScrollPhysics(),
                builder: (BuildContext context, int index) {
                  return PhotoViewGalleryPageOptions(
                    imageProvider: NetworkImage(widget.photoList[index]),
                    initialScale: PhotoViewComputedScale.contained * 1,
                    heroAttributes:
                        PhotoViewHeroAttributes(tag: widget.photoList[index]),
                  );
                },
                itemCount: widget.photoList.length,
                // loadingChild: widget.loadingChild,
                backgroundDecoration: BoxDecoration(
                  color: Colors.black,
                ),
                pageController: PageController(initialPage: initialIndex),
                //点进去哪页默认就显示哪一页
                onPageChanged: onPageChanged,
              ),
              GestureDetector(
                onTap: () {
                  PermissionUtil.checkStoragePermission().then((isGranted) {
                    if (isGranted) {
                      //有权限
                      _saveImage(imgUrl);
                    }
                  });
                },
                child: Container(
                  padding: const EdgeInsets.all(10.0),
                  child: Icon(
                    Icons.save_alt,
                    color: Colors.white,
                  ),
                ),
              )
            ],
          )),
    );
  }
}
